package org.feit.findword;
import java.util.List;

import org.feit.findword.data.Score;
import org.feit.findword.data.ScoreProcessor;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class HighScores extends Activity {

	static final int HIGH_SCORE_DIALOG = 0;

	private ListView mScoresList;
	private ScoresListAdapter mListAdapter;
	private AlertDialog mHighScoreDialog;
	private EditText mName;
	private ScoreProcessor mScoreProcessor;
	private int mScore;
	private int mBoardSize;
	private Bundle mGameBundle;
	private boolean mIsHighScore;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.high_scores);
		setTitle(getString(R.string.high_scores_top));
		createDialogs();
		mScoreProcessor = new ScoreProcessor(this);
		mGameBundle = getIntent().getExtras();
		if (mGameBundle != null) {
			mScore = mGameBundle.getInt("score");
			mBoardSize = mGameBundle.getInt("boardSize");
			checkHighScores();
		} else {
			loadPreferences(this);
			Button btn = (Button) findViewById(R.id.btnMissedWords);
			btn.setVisibility(View.INVISIBLE);
			btn = (Button) findViewById(R.id.btnNewGame);
			btn.setVisibility(View.INVISIBLE);
		}
		mScoresList = (ListView) findViewById(R.id.scores_list);
		mScoresList.setEmptyView(findViewById(R.id.no_high_scores));
		List<Score> scores = mScoreProcessor.getHighScores(mBoardSize);
		mListAdapter = new ScoresListAdapter(this, scores);
		mScoresList.setAdapter(mListAdapter);
	}

	private void checkHighScores() {
		setProgressBarIndeterminateVisibility(true);
		Thread t = new Thread(mHighScoreRunnable);
		t.start();
	}

	final Runnable mHighScoreRunnable = new Runnable() {

		@Override
		public void run() {
			mIsHighScore = mScoreProcessor.isHighScore(mScore, mBoardSize);
			mHighScoreHandler.sendEmptyMessage(0);
		}
	};

	final Handler mHighScoreHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			setProgressBarIndeterminateVisibility(false);
			if (mIsHighScore) {
				showDialog(HIGH_SCORE_DIALOG);
			}
		}

	};

	private void saveScore() {
		setProgressBarIndeterminateVisibility(true);
		Thread t = new Thread(mSaveScoreRunnable);
		t.start();
	}

	final Runnable mSaveScoreRunnable = new Runnable() {

		@Override
		public void run() {
			String name = mName.getText().toString();
			if (name.length() <= 0) {
				name = getString(R.string.uknonwn);
			}
			if (name.length() > 20) {
				name = name.substring(0, 20);
			}
			mScoreProcessor.addHighScore(name, mScore, mBoardSize);
			mSaveScoreHandler.sendEmptyMessage(0);
		}
	};

	final Handler mSaveScoreHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			setProgressBarIndeterminateVisibility(false);
			reloadScores();
		}

	};

	private void loadPreferences(Context c) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(c);

		String str = prefs.getString("boardSize", "16");
		mBoardSize = Integer.parseInt(str);
	}

	private void reloadScores() {
		List<Score> scores = mScoreProcessor.getHighScores(mBoardSize);
		mListAdapter.refreshDataSet(this, scores);
	}

	private void createDialogs() {
		final View highScoreView = LayoutInflater.from(this).inflate(
				R.layout.new_high_score, null);
		mName = (EditText) highScoreView.findViewById(R.id.name);

		mHighScoreDialog = new AlertDialog.Builder(this).setTitle(
				R.string.new_high_score).setView(highScoreView)
				.setPositiveButton(R.string.save,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								dialog.dismiss();
								saveScore();
							}
						}).setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						}).create();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == HIGH_SCORE_DIALOG) {
			return mHighScoreDialog;
		}
		return super.onCreateDialog(id);
	}

	public void onBtnClick(View v) {
		if (v.getId() == R.id.btnMissedWords) {
			Intent intent = new Intent(this, MissedWords.class);
			intent.putExtras(mGameBundle);
			startActivity(intent);
		}
		if (v.getId() == R.id.btnNewGame) {
			Intent intent = new Intent("org.feit.findword.action.NEW_GAME");
			startActivity(intent);
			finish();
		}
	}
}
